package com.siao.component
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.PixelSnapping;
	import flash.events.Event;
	import flash.geom.Point;
	
	/**
	 * 位图逐帧克隆
	 * @author SiaoLeon
	 */
	public class BitmapClone extends Bitmap
	{
		// -------------------------------------------------------------------------------------------------------- 静态常量
		
		// -------------------------------------------------------------------------------------------------------- 静态变量
		
		// -------------------------------------------------------------------------------------------------------- 静态方法
		
		// -------------------------------------------------------------------------------------------------------- 静态函数
		
		// -------------------------------------------------------------------------------------------------------- 属性
		
		private var _target:DisplayObject
		
		public function get target():DisplayObject
		{
			return this._target;
		}
		
		public function set target(value:DisplayObject):void
		{
			this._target = value;
			
			this.redraw();
		}
		
		// -------------------------------------------------------------------------------------------------------- 变量
		
		// -------------------------------------------------------------------------------------------------------- 构造
		
		/**
		 * 构造函数
		 * @param target 克隆对象
		 */
		public function BitmapClone(target:DisplayObject=null)
		{
			super(null, PixelSnapping.ALWAYS, true);
			
			this.target = target;
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
		}
		
		// -------------------------------------------------------------------------------------------------------- 方法
		
		/**
		 * 重绘
		 */
		protected function redraw():void
		{
			if (this.target == null)
			{
				return;
			}
			
			if (this.target.parent != null && !this.target.parent.contains(this))
			{
				this.target.parent.addChild(this);
			}
			
			if (this.stage == null)
			{
				return;
			}
			
			if (this.target.parent == null)
			{
				this.parent.addChild(this.target);
			}
			
			var meta:Point = new Point(this.target.x, this.target.y);
			this.x = this.parent.globalToLocal(meta).x;
			this.y = this.parent.globalToLocal(meta).y;
			
			if (this.alpha != this.target.alpha)
			{
				this.alpha = this.target.alpha;
			}
			
			this.target.visible = false;
			
			if (this.bitmapData == null)
			{
				return;
			}
			
			this.bitmapData.draw(this.target, null, null, null, null, true);
		}
		
		// -------------------------------------------------------------------------------------------------------- 函数
		
		private function onAddedToStage(event:Event):void
		{
			this.bitmapData = new BitmapData(this.stage.stageWidth, this.stage.stageHeight, true, 0);
			this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(event:Event):void
		{
			this.redraw();
		}
	
	}
}

